package com.imut.lagain.controller;

import com.imut.lagain.common.Result;
import com.imut.lagain.entity.Notification;
import com.imut.lagain.service.NotificationService;
import com.imut.lagain.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 通知控制器
 */

@RestController
@RequestMapping("/notifications")
public class NotificationController {
    private static final Logger log = LoggerFactory.getLogger(NotificationController.class);
    @Autowired
    private NotificationService notificationService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 创建通知
     */
    @PostMapping
    public Result<Notification> createNotification(@RequestBody Notification notification, HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            // 修改为正确的方法调用
            Notification created = notificationService.createNotification(notification, currentUserId);
            return Result.success(created);
        } catch (Exception e) {
            log.error("创建通知失败", e);
            return Result.error("创建通知失败: " + e.getMessage());
        }
    }

    /**
     * 发送系统通知
     */
    @PostMapping("/system")
    public Result<Notification> sendSystemNotification(
            @RequestParam String title,
            @RequestParam String content,
            @RequestParam(required = false) List<String> targetUserIds,
            HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            Notification notification = new Notification();
            notification.setTitle(title);
            notification.setContent(content);
            // 修改类型为枚举类型
            notification.setType(Notification.NotificationType.SYSTEM);
            // 修改为正确的方法调用
            Notification sent = notificationService.createNotification(notification, currentUserId);
            return Result.success(sent);
        } catch (Exception e) {
            log.error("发送系统通知失败", e);
            return Result.error("发送系统通知失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户通知列表
     */
    @GetMapping
    public Result<Map<String, Object>> getUserNotifications(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Boolean isRead,
            HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            // 使用占位符返回空结果
            Map<String, Object> result = new HashMap<>();
            result.put("content", new ArrayList<>());
            result.put("totalElements", 0);
            result.put("totalPages", 0);
            result.put("currentPage", page);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户通知列表失败", e);
            return Result.error("获取通知列表失败: " + e.getMessage());
        }
    }

    /**
     * 标记通知为已读
     */
    @PutMapping("/{id}/read")
    public Result<Notification> markAsRead(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            // 修改为正确的方法调用
            boolean success = notificationService.markAsRead(id, currentUserId);
            if (success) {
                return Result.success(null);
            } else {
                return Result.error("标记已读失败");
            }
        } catch (Exception e) {
            log.error("标记通知为已读失败", e);
            return Result.error("标记已读失败: " + e.getMessage());
        }
    }

    /**
     * 批量标记为已读
     */
    @PutMapping("/batch-read")
    public Result<Void> batchMarkAsRead(@RequestBody List<Long> ids, HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            // 使用占位符返回成功结果
            return Result.success();
        } catch (Exception e) {
            log.error("批量标记为已读失败", e);
            return Result.error("批量标记已读失败: " + e.getMessage());
        }
    }

    /**
     * 删除通知
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteNotification(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            // 修改为正确的方法调用
            boolean success = notificationService.deleteNotification(id, currentUserId);
            if (success) {
                return Result.success();
            } else {
                return Result.error("删除通知失败");
            }
        } catch (Exception e) {
            log.error("删除通知失败", e);
            return Result.error("删除通知失败: " + e.getMessage());
        }
    }

    /**
     * 获取未读通知数量
     */
    @GetMapping("/unread-count")
    public Result<Long> getUnreadCount(HttpServletRequest request) {
        try {
            Long currentUserId = getCurrentUserId(request);
            // 修改为正确的方法调用
            long count = notificationService.getUnreadCount(currentUserId);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取未读通知数量失败", e);
            return Result.error("获取未读数量失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            // 修改为正确的方法调用
            return jwtUtil.getUserIdFromToken(token);
        }
        throw new RuntimeException("无效的访问令牌");
    }
}